package io.lckgroup.modules.lck.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.lckgroup.common.utils.PageUtils;
import io.lckgroup.modules.lck.dao.*;
import io.lckgroup.modules.lck.entity.*;
import io.lckgroup.modules.lck.entity.wxmpvo.ShopFoodEntityWeixinVo;
import io.lckgroup.modules.lck.entity.wxmpvo.ShopFoodSpecEntityWeixinVo;
import io.lckgroup.modules.lck.form.OrderMainEntityWeixinForm;
import io.lckgroup.modules.lck.form.wxgzh.OrderDetailWxgzhForm;
import io.lckgroup.modules.lck.form.wxgzh.OrderEntityWxgzhForm;
import io.lckgroup.modules.lck.form.wxgzh.OrderMainMerchantWxgzhFrom;
import io.lckgroup.modules.lck.form.wxgzh.ShopFoodEntityWxgzhForm;
import io.lckgroup.modules.lck.service.OrderService;
import io.lckgroup.modules.lck.utils.GetPayPage;
import io.lckgroup.modules.lck.utils.MakeOrderIdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: OrderServiceImpl
 * @Description: TODO
 * @Author: zhao_ag
 * @Date: 2020-03-20 10:49
 * @Version: 1.0
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMainDao orderMainDao;

    @Autowired
    private OrderDetailDao orderDetailDao;

    @Autowired
    private ShopMerchantInfoDao shopMerchantInfoDao;

    @Autowired
    private ShopFoodDao shopFoodDao;

    @Autowired
    private ShopFoodSpecDao shopFoodSpecDao;

    /**
     * 计算订单总价（公众号）
     *
     * @param foodList
     * @return
     */
    @Override
    public BigDecimal countOrderPrice(List<ShopFoodEntityWxgzhForm> foodList) {
        BigDecimal price = new BigDecimal(0);
        BigDecimal orderPrice = new BigDecimal(0);
        for (ShopFoodEntityWxgzhForm shopFoodEntityWxgzhForm : foodList) {
            //如果有规格去就去相应的表查价格
            if (shopFoodEntityWxgzhForm.getSpecsId() != null) {
                QueryWrapper<ShopFoodSpecEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("id", shopFoodEntityWxgzhForm.getSpecsId()).select("price");
                ShopFoodSpecEntity shopFoodSpecEntity = shopFoodSpecDao.selectOne(queryWrapper);
                //单价*数量
                price = shopFoodSpecEntity.getPrice().multiply(new BigDecimal(shopFoodEntityWxgzhForm.getCount()));
            } else {
                QueryWrapper<ShopFoodEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("id", shopFoodEntityWxgzhForm.getId()).select("price");
                ShopFoodEntity shopFoodEntity = shopFoodDao.selectOne(queryWrapper);
                price = shopFoodEntity.getPrice().multiply(new BigDecimal(shopFoodEntityWxgzhForm.getCount()));
            }
            orderPrice = orderPrice.add(price);
        }
        return orderPrice;
    }

    @Override
    public OrderMainEntity createOrder(OrderMainEntity orderMainEntity, BigDecimal orderPrice, String orderNum, OrderEntityWxgzhForm orderEntityWxgzhForm, CustomerInfoEntity customerInfoEntity) {
        //判断是否有菜品在下单期间修改过
        List foodIdList = new ArrayList();
        for (ShopFoodEntityWxgzhForm shopFoodEntityWxgzhForm : orderEntityWxgzhForm.getFoodList()) {
            foodIdList.add(shopFoodEntityWxgzhForm.getId());
        }
        List<ShopFoodEntity> shopFoodEntityList = shopFoodDao.selectBatchIds(foodIdList);
        for (ShopFoodEntityWxgzhForm vo : orderEntityWxgzhForm.getFoodList()) {
            for (ShopFoodEntity vo1 : shopFoodEntityList) {
//                菜品id相同时
                if (vo.getId() == vo1.getId()) {
                    if (!vo.getGmtModified().equals(vo1.getGmtModified())) {
                        System.out.println("当前菜品ID：" + vo.getId() + "-------" + vo.getGmtModified() + "--------菜品更新时间不一致--------" + vo1.getGmtModified());
                        return null;
                    }
                }

            }
        }
        //计算订单商品数量
        Integer orderCount = 0;
        for (ShopFoodEntityWxgzhForm shopFoodEntityWxgzhForm : orderEntityWxgzhForm.getFoodList()) {
            orderCount += shopFoodEntityWxgzhForm.getCount();
        }
        //将主订单数据set进对应entity
        orderMainEntity.setMerchantId(orderEntityWxgzhForm.getMerchantId());
        orderMainEntity.setCustomerRemarks(orderEntityWxgzhForm.getCustomerRemarks());
        orderMainEntity.setGoodsNum(orderCount);
        orderMainEntity.setOrderId(orderNum);
        orderMainEntity.setOrderPrice(orderPrice);
        orderMainEntity.setOrderType(2);
        orderMainEntity.setPeopleNum(orderEntityWxgzhForm.getPeopleNum());
        orderMainEntity.setCustomerTel(orderEntityWxgzhForm.getCustomerTel());
        orderMainEntity.setAppointmentTime(orderEntityWxgzhForm.getAppointmentTime());
        orderMainEntity.setCustomerId(customerInfoEntity.getId());
        //插入主订单
        orderMainDao.insert(orderMainEntity);
        //同时查询出主订单id
        QueryWrapper<OrderMainEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(orderMainEntity);
        OrderMainEntity om = orderMainDao.selectOne(queryWrapper);
        //主订单id
        Long mainOrderId = om.getId();
        //插入订单明细
        for (ShopFoodEntityWxgzhForm shopFoodEntityWxgzhForm : orderEntityWxgzhForm.getFoodList()) {
            OrderDetailEntity orderDetailEntity = new OrderDetailEntity();
            //遍历将菜品明细插入
            orderDetailEntity.setOrderMainId(mainOrderId);
            orderDetailEntity.setFoodId(shopFoodEntityWxgzhForm.getId());
            orderDetailEntity.setFoodNum(shopFoodEntityWxgzhForm.getCount());
            orderDetailEntity.setFoodPrice(shopFoodEntityWxgzhForm.getPrice());
            orderDetailEntity.setFoodSpecs(shopFoodEntityWxgzhForm.getSpecsName());
            orderDetailEntity.setFoodName(shopFoodEntityWxgzhForm.getFoodName());
            orderDetailEntity.setImgUrl(shopFoodEntityWxgzhForm.getImgUrl());
            orderDetailDao.insert(orderDetailEntity);
        }

        return om;
    }

    @Override
    public List<OrderDetailEntity> getOrderDetail(Long id) {
        //根据主订单id查询所有的订单明细
        QueryWrapper<OrderDetailEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_main_id", id);
        List<OrderDetailEntity> orderDetailEntityList = orderDetailDao.selectList(queryWrapper);
        return orderDetailEntityList;
    }

    @Override
    public boolean isMerchinfoOpen(Long merchinfo_id) {
        boolean isOpen = false;
        ShopMerchantInfoEntity shopMerchantInfoEntity = shopMerchantInfoDao.selectById(merchinfo_id);
        if (shopMerchantInfoEntity.getIsOpen() == 1) {
            isOpen = true;
        }
        return isOpen;
    }

    /**
     * 根据用户id查询订单（按订单状态分页查询）
     *
     * @param params（里面包含分页参数及订单状态参数）
     * @param customerInfoEntity
     * @return
     */
    @Override
    public PageUtils getOrderByState(Map<String, Object> params, CustomerInfoEntity customerInfoEntity) {
        //分页参数
        Page page = new Page<>(Integer.valueOf(params.get("page").toString()), Integer.valueOf(params.get("limit").toString()));
        //订单状态参数
        String orderState = params.get("orderState").toString();
        //商家id
        String merchantId = params.get("merchantId").toString();
        IPage<OrderMainMerchantWxgzhFrom> iPage = orderMainDao.getOrderByState(page, orderState, customerInfoEntity.getId(), merchantId);
        return new PageUtils(iPage);

    }

    /**
     * 功能描述: <br>
     * 〈〉生成订单
     *
     * @Param: [orderMainEntity_weixin_form]
     * @Return: io.lckgroup.modules.lck.entity.OrderMainEntity
     * @Author: 13980
     * @Date: 2020/3/19 10:24
     */
    @CacheEvict(value = "weixinGetOrderList", key = "#orderMainEntity_weixin_form.merchantId")
    @Override
    @Transactional
    public OrderMainEntity makeOrder(OrderMainEntityWeixinForm orderMainEntity_weixin_form) {
        List<ShopFoodEntityWeixinVo> foodList = orderMainEntity_weixin_form.getFoodList();
//        判断是否有菜品规格被修改过的菜品ID集合
        ArrayList<Integer> foodAllIdList = new ArrayList<>();
        ArrayList<Integer> foodIdList1 = new ArrayList<>();
        ArrayList<Integer> specIdList1 = new ArrayList<>();
        for (ShopFoodEntityWeixinVo shopFoodEntity_weixin_vo : foodList) {
            foodAllIdList.add(shopFoodEntity_weixin_vo.getId().intValue());
//           判断是否有规格
            if (shopFoodEntity_weixin_vo.getIsSpecs() == 0) {
//                无规格
                foodIdList1.add(shopFoodEntity_weixin_vo.getId().intValue());
            } else {
//               有规格
                List<ShopFoodSpecEntityWeixinVo> specEntityList = shopFoodEntity_weixin_vo.getSpecEntityList();
                for (ShopFoodSpecEntityWeixinVo vo : specEntityList) {
//                    有效规格
                    if (vo.getCount() > 0) {
                        specIdList1.add(vo.getId().intValue());
                    }
                }
            }
        }
//        所有的菜品
        List<ShopFoodEntity> batchIds = shopFoodDao.selectBatchIds(foodAllIdList);
        for (ShopFoodEntityWeixinVo vo : foodList) {
            for (ShopFoodEntity vo1 : batchIds) {
//                菜品id相同时
                if (vo.getId() == vo1.getId()) {
                    if (!vo.getGmtModified().equals(vo1.getGmtModified())) {
                        System.out.println("当前菜品ID：" + vo.getId() + "-------" + vo.getGmtModified() + "--------菜品更新时间不一致--------" + vo1.getGmtModified());
                        return null;
                    }
                }

            }
        }
//        操作foodIdList
        List<ShopFoodEntity> foodList2;
        BigDecimal money1 = new BigDecimal(0);
        BigDecimal money2 = new BigDecimal(0);
        if (foodIdList1.size() > 0) {
            foodList2 = shopFoodDao.selectBatchIds(foodIdList1);
            BigDecimal moneydellFoodmoney = new BigDecimal("0");
            for (ShopFoodEntityWeixinVo vo : foodList) {
                for (ShopFoodEntity entity : foodList2) {
//                如果vo.id == entity.id 同一菜品时
                    if (vo.getId() == entity.getId()) {
//                    在vo中取数量  在entity中取价格
                        BigDecimal count = new BigDecimal(vo.getCount());
                        BigDecimal price = entity.getPrice();
                        BigDecimal temp = count.multiply(price);
                        moneydellFoodmoney = moneydellFoodmoney.add(temp);
                    }
                }
            }
            money1 = moneydellFoodmoney;
        }
//        操作规格 specIdList
        List<ShopFoodSpecEntity> specList;
        if (specIdList1.size() > 0) {
            specList = shopFoodSpecDao.selectBatchIds(specIdList1);
            BigDecimal moneyTemp = new BigDecimal("0");
            for (ShopFoodEntityWeixinVo vo : foodList) {
                List<ShopFoodSpecEntityWeixinVo> specCountList = vo.getSpecEntityList();
                for (ShopFoodSpecEntityWeixinVo vo_count : specCountList) {
                    if (vo_count.getCount() > 0) {
//                    vo_count获取count entity获取价格
                        for (ShopFoodSpecEntity entity : specList) {
//                        规格id相等
                            if (entity.getId() == vo_count.getId()) {
                                BigDecimal count = new BigDecimal(vo_count.getCount());
                                BigDecimal price = entity.getPrice();
                                BigDecimal temp = count.multiply(price);
                                moneyTemp = moneyTemp.add(temp);
                            }
                        }
                    }
                }
            }
            money2 = moneyTemp;
        }
        //        后台总价格
        BigDecimal money = money1.add(money2);
        OrderMainEntity mainEntity = new OrderMainEntity();
//        生成订单id
        String orderId = MakeOrderIdUtil.makeOrderId();
        mainEntity.setOrderId(orderId);
//        商家ID
        mainEntity.setMerchantId(orderMainEntity_weixin_form.getMerchantId());
//        桌子号码
        mainEntity.setTableNum(orderMainEntity_weixin_form.getTableNum());
//        总金额
        mainEntity.setOrderPrice(money);
//        用户id
        mainEntity.setCustomerId(orderMainEntity_weixin_form.getCustomerId());
//        备注
        mainEntity.setCustomerRemarks(orderMainEntity_weixin_form.getCustomerRemarks());
//        人数
        mainEntity.setPeopleNum(orderMainEntity_weixin_form.getPeopleNum());
        int num = 0;
        List<ShopFoodEntityWeixinVo> foodListNum = orderMainEntity_weixin_form.getFoodList();
        for (ShopFoodEntityWeixinVo vo : foodListNum) {
            if (vo.getIsSpecs() == 0) {
                num += vo.getCount();
            } else {
                List<ShopFoodSpecEntityWeixinVo> entityList = vo.getSpecEntityList();
                for (ShopFoodSpecEntityWeixinVo vo1 : entityList) {
                    num += vo1.getCount();
                }
            }
        }
//        商品数量
        mainEntity.setGoodsNum(num);
//        到店支付  小程序到店订单
        mainEntity.setOrderType(1);
        int insert = orderMainDao.insert(mainEntity);
//        查询刚刚插入的订单主表数据查询出来获取id
        QueryWrapper<OrderMainEntity> wrapper = new QueryWrapper<>();
        wrapper.setEntity(mainEntity);
        OrderMainEntity one = orderMainDao.selectOne(wrapper);
//        订单明细表生成  包括订单ID 菜品ID 价格 数量 规格 规格名称 图片 菜品名称
        List<ShopFoodEntityWeixinVo> foodListVo = orderMainEntity_weixin_form.getFoodList();
        List<OrderDetailEntity> entityList = new ArrayList<OrderDetailEntity>();
        for (ShopFoodEntityWeixinVo food : foodListVo) {
            if (food.getIsSpecs() != 1) {
//                没有规格的
                OrderDetailEntity entity = new OrderDetailEntity();
                entity.setFoodId(food.getId());
                entity.setFoodNum(food.getCount());
                entity.setFoodName(food.getGoodsName());
                entity.setImgUrl(food.getImgUrl());
                entity.setFoodPrice(food.getPrice());
                entity.setOrderMainId(one.getId());
                entityList.add(entity);
            } else {
//                有规格的
                List<ShopFoodSpecEntityWeixinVo> specEntityList = food.getSpecEntityList();
                for (ShopFoodSpecEntityWeixinVo vo : specEntityList) {
                    if (vo.getCount() > 0) {
                        OrderDetailEntity entity = new OrderDetailEntity();
                        entity.setFoodId(vo.getGoodsId());
                        entity.setFoodSpecs(vo.getSpecsName());
                        entity.setFoodNum(vo.getCount());
                        entity.setFoodPrice(vo.getPrice());
                        entity.setImgUrl(food.getImgUrl());
                        entity.setFoodName(food.getGoodsName());
                        entity.setOrderMainId(one.getId());
                        entityList.add(entity);
                    }
                }
            }
        }
        for (OrderDetailEntity orderDetailEntity : entityList) {
            orderDetailDao.insert(orderDetailEntity);
        }
//        做一个redis的定时任务
        return one;
    }

    /**
     * 功能描述: <br>
     * 〈〉查询订单主表
     *
     * @Param: [customInfoId , MerchantInfoId]
     * @Return: java.util.List<io.lckgroup.modules.lck.entity.OrderMainEntity>
     * @Author: 13980
     * @Date: 2020/3/9 13:36
     */
    @Override
    @Transactional
    @Cacheable(value = "weixinGetOrderList", key = "#MerchantInfoId")
    public List<OrderMainEntity> getOrderList(Long customInfoId, Long MerchantInfoId) {
        // 存储所有订单数据
        List<OrderMainEntity> list = new ArrayList();
        OrderMainEntity entity = new OrderMainEntity();
        entity.setCustomerId(customInfoId);
        entity.setMerchantId(MerchantInfoId);
        QueryWrapper<OrderMainEntity> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        wrapper.setEntity(entity);
        try {
            list = orderMainDao.selectList(wrapper);
        } catch (Exception e) {

        }
        for (OrderMainEntity ll : list) {
            System.out.println(ll.getId());
        }
        return list;
    }

    /**
     * 功能描述: <br>
     * 〈〉查询订单明细表
     *
     * @Param: [orderMainId]
     * @Return: io.lckgroup.modules.lck.form.wxgzh.OrderDetailWxgzhForm
     * @Author: 13980
     * @Date: 2020/3/10 10:28
     */
    @Override
    @Transactional
    public List<OrderDetailWxgzhForm> getOrderDetailWxmp(Long orderMainId) {
        List<OrderDetailWxgzhForm> list = new ArrayList<>();
//      查询订单明细
        OrderDetailEntity entity = new OrderDetailEntity();
        entity.setOrderMainId(orderMainId);
        QueryWrapper<OrderDetailEntity> wrapper = new QueryWrapper<>();
        wrapper.setEntity(entity);
        List<OrderDetailEntity> list1 = orderDetailDao.selectList(wrapper);
        for (OrderDetailEntity odl : list1) {
            //        查询菜品名称和图片
            ShopFoodEntity foodEntity = shopFoodDao.selectById(odl.getFoodId());
            OrderDetailWxgzhForm form = new OrderDetailWxgzhForm(odl, foodEntity.getGoodsName(), foodEntity.getImgUrl());
            list.add(form);
        }
        return list;
    }

    /**
     * 功能描述: <br>
     * 〈〉支付接口
     *
     * @Param: [orderId]
     * @Return: java.lang.String
     * @Author: 13980
     * @Date: 2020/3/11 11:01
     */
    @Override
    @Transactional
    public String topayweixin(String orderId, long MerchantInfoId) {
//        根据订单号查询订单
        OrderMainEntity entity = new OrderMainEntity();
        entity.setOrderId(orderId);
        QueryWrapper<OrderMainEntity> wrapper = new QueryWrapper<>();
        wrapper.setEntity(entity);
        OrderMainEntity one = orderMainDao.selectOne(wrapper);
//      根据商家id查询商家
        ShopMerchantInfoEntity shop = new ShopMerchantInfoEntity();
        shop.setId(MerchantInfoId);
        QueryWrapper<ShopMerchantInfoEntity> wrapper1 = new QueryWrapper<>();
        wrapper1.setEntity(shop);
        ShopMerchantInfoEntity shopOne = shopMerchantInfoDao.selectOne(wrapper1);
        String userAgent = "WeiXIN";
        String successUrl = "/pages/user/user";
        String merchantNo = shopOne.getMerchantNo();
        String storeNo = shopOne.getStoreNo();
        String posNum = shopOne.getPosNum();
        String outTradeNo = one.getOrderId();
        BigDecimal orderPrice = one.getOrderPrice();
        String url = GetPayPage.getpaypage(merchantNo, storeNo, posNum, userAgent, outTradeNo, successUrl, orderPrice);
        return url;
    }

    /**
     * 功能描述: <br>
     * 〈〉订单重新支付
     *
     * @Param: [orderMainId]
     * @Return: java.lang.String
     * @Author: 13980
     * @Date: 2020/3/18 13:55
     */
    @CacheEvict(value = "weixinGetOrderList", key = "#MerchantInfoId")
    @Override
    @Transactional
    public OrderMainEntity updateOrderId(Long id, long MerchantInfoId) {
        OrderMainEntity entity = new OrderMainEntity();
        entity.setId(id);
        String orderId = MakeOrderIdUtil.makeOrderId();
        entity.setOrderId(orderId);
        int i = orderMainDao.updateById(entity);
        QueryWrapper<OrderMainEntity> wrapper = new QueryWrapper<>();
        wrapper.setEntity(entity);
        OrderMainEntity selectOne = orderMainDao.selectOne(wrapper);
        return selectOne;
    }

    @Override
    @Transactional
    @CacheEvict(value = "weixinGetOrderList", allEntries = true)
    public int cancelOrder(String orderNum) {
        QueryWrapper<OrderMainEntity> queryWrapper = new QueryWrapper<>();
        OrderMainEntity orderMainEntity = new OrderMainEntity();
        orderMainEntity.setIsPay(2);
        queryWrapper.eq("order_id", orderNum);
        int result = orderMainDao.update(orderMainEntity, queryWrapper);
        return result;
    }

    /**
     * 功能描述: <br>
     * 〈〉查询是否有下架菜品
     *
     * @Param: [orderMainEntity_weixin_form]
     * @Return: java.util.List<io.lckgroup.modules.lck.entity.ShopFoodEntity>
     * @Author: 13980
     * @Date: 2020/3/25 15:57
     */
    @Override
    @Transactional
    public List<ShopFoodEntity> isuper(List<Long> idList) {
        List<ShopFoodEntity> ent = new ArrayList<>();
        List<ShopFoodEntity> shopFoodEntities = shopFoodDao.selectBatchIds(idList);
        for (ShopFoodEntity shopFoodEntity : shopFoodEntities) {
//            是否下架。或者被删除
            if (shopFoodEntity.getIsUpper() == 0 || shopFoodEntity.getIsDelete() == 1) {
                ent.add(shopFoodEntity);
            }
        }
        return ent;
    }

    @Override
    @Transactional
    public List<Long> getFoodIdList(Long orderID) {
        //        用订单主表中的id查询订单明细表，然后取出菜品id集合
        OrderDetailEntity detailEntity = new OrderDetailEntity();
        detailEntity.setOrderMainId(orderID);
        QueryWrapper<OrderDetailEntity> wrapper1 = new QueryWrapper();
        wrapper1.setEntity(detailEntity);
        List<OrderDetailEntity> list = orderDetailDao.selectList(wrapper1);
        List<Long> idList = new ArrayList<Long>();
        for (OrderDetailEntity orderDetailEntity : list) {
            idList.add(orderDetailEntity.getFoodId());
        }
        return idList;
    }
}
